package visitor;

import operatori.Impartit;
import operatori.Minus;
import operatori.Ori;
import operatori.Plus;
import functii.elementare.Constanta;
import functii.elementare.Necunoscuta;
import functii.trigonometrice.Cos;
import functii.trigonometrice.Sin;

public class CalculVisitor extends Visitor {
	double rez;
	
	public CalculVisitor() {
		rez=0;
	}
	
	public CalculVisitor(double rez) {
		this.rez = rez;
	}
	
	
	public void visit(Plus n) {
		if (n.getFStang()!=null && n.getFDrept()!=null) {
			visit(n.getFStang());
			double rez1 = rez;
			visit(n.getFDrept());
			double rez2 = rez;
			rez = rez1 + rez2;
		}

	}

	
	public void visit(Minus n) {
		if (n.getFStang()!=null && n.getFDrept()!=null) {
			visit(n.getFStang());
			double rez1 = rez;
			visit(n.getFDrept());
			double rez2 = rez;
			rez = rez1 - rez2;
		}

	}

	
	public void visit(Impartit n) {
		if (n.getFStang()!=null && n.getFDrept()!=null) {
			visit(n.getFStang());
			double rez1 = rez;
			visit(n.getFDrept());
			double rez2 = rez;	
			if (rez2==0) {
				System.out.println("Error: Division by zero!");
				System.exit(1);
			} else {
				rez = rez1 / rez2;
			}
		}

	}

	
	public void visit(Ori n) {
		if (n.getFStang()!=null && n.getFDrept()!=null) {
			visit(n.getFStang());
			double rez1 = rez;
			visit(n.getFDrept());
			double rez2 = rez;
			rez = rez1 * rez2;
		}

	}

	
	public void visit(Necunoscuta n) {
		rez = n.getX();

	}

	
	public void visit(Constanta c) {
		rez = c.getCt();

	}

	
	public void visit(Sin n) {
		if (n.getFStang()!=null) {
			visit(n.getFStang());
			double rez1 = rez;
			rez = Math.sin(rez1);
		}

	}

	
	public void visit(Cos n) {
		if (n.getFStang()!=null) {
			visit(n.getFStang());
			double rez1 = rez;
			rez = Math.cos(rez1);
		}

	}
	
	
	public String toString() {
		return String.valueOf(rez);
	}

	public double getRezultat() {
		return rez;
	}
}
